package json.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import member.domain.Member;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String cmd = request.getParameter("cmd");
		if(cmd.equals("searchMemberById")){
			searchMemberId(request, response);
		}else if(cmd.equals("getSubwayLine")){
			getSubwayLine(request, response);
		}
	}

	protected void searchMemberId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		//비지니스 로직
		Member m = new Member(id, "김철수", "kim@a.com", 3000, true);
		//응답 - JSON 형태 문자열로 응답.
		JSONObject obj = new JSONObject(m);
		
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.println(obj);
	}
	protected void getSubwayLine(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String city = request.getParameter("city");
		JSONArray obj = new JSONArray(findSubwayLine(city));
		
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.println(obj);
	}
	
	private ArrayList findSubwayLine(String city){
		ArrayList lines = new ArrayList();
		if(city.equals("서울")){
			lines.add("1호선");
			lines.add("2호선");
			lines.add("3호선");
			lines.add("4호선");
			lines.add("5호선");
			lines.add("6호선");
			lines.add("7호선");
			lines.add("8호선");
			lines.add("9호선");
			lines.add("분단선");
			lines.add("신분단선");
		}else if(city.equals("부산")){
			lines.add("1호선");
			lines.add("2호선");
			lines.add("3호선");
			lines.add("4호선");
			lines.add("김해선");
		}else if(city.equals("대구") || city.equals("인천")){
			lines.add("1호선");
			lines.add("2호선");
		}else{
			lines.add("1호선");
		}
		return lines;
	}
}
